package net.lovesrc.support.service.picprocess;

import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;


/**
 * 根据Thumbnails实现的文件处理服务
 * https://github.com/thumbor/thumbor
 *
 * @author gelic
 * Created in 16:10 2018/10/27
 * @since
 */
public class ThumbnailsPicServiceImpl implements PicService {

    private static final Logger logger = LoggerFactory.getLogger(ThumbnailsPicServiceImpl.class);

    @Override
    public void Thum(InputStream is, OutputStream os) throws IOException {
        Thum(is, DEFUALT_SCALT, DEFUALT_QUALITY, os);
    }

    @Override
    public void Thum(InputStream is, double scale, float quality, OutputStream os) throws IOException {
        Thumbnails.of(is)
                .scale(scale)
                .outputQuality(quality)
                .toOutputStream(os);
    }

    @Override
    public void Thum(File inputFile, double scale, float quality, File outputFile) throws IOException {
        Thumbnails.of(inputFile)
                .scale(scale)
                .outputQuality(quality)
                .toFile(outputFile);
    }

    @Override
    public void watermark(InputStream is, String outputFomat, WatermarkConfig watermarkConfig, OutputStream os) throws IOException {
        BufferedImage image = ImageIO.read(is);
        BufferedImage watermarkImage = drawTranslucentStringPic(image.getWidth(), image.getHeight(), watermarkConfig);

        Thumbnails.of(image)
                .scale(watermarkConfig.getScale())
                .outputQuality(watermarkConfig.getQuality())
                .watermark(watermarkConfig.getPositions(), watermarkImage, watermarkConfig.getOpacity())
                .outputFormat(StringUtils.isNotEmpty(outputFomat) ? outputFomat : watermarkConfig.getOutputFormat())
                .toOutputStream(os);
    }

    @Override
    public void watermark(File inputFile, String content, File outputFile) throws IOException {
        watermark(inputFile, content, outputFile);
    }

    @Override
    public void watermark(File inputFile, WatermarkConfig watermarkConfig, File outputFile) throws IOException {
        BufferedImage image = ImageIO.read(new FileInputStream(inputFile));
        BufferedImage watermarkImage = drawTranslucentStringPic(image.getWidth(), image.getHeight(), watermarkConfig);

        Thumbnails.Builder<File> watermarkBuilder = Thumbnails.of(inputFile)
                .scale(watermarkConfig.getScale())
                .outputQuality(watermarkConfig.getQuality())
                .watermark(watermarkConfig.getPositions(), watermarkImage, watermarkConfig.getOpacity());
        if(StringUtils.isNotEmpty(watermarkConfig.getOutputFormat())) {
            watermarkBuilder.outputFormat(watermarkConfig.getOutputFormat());
        }
        watermarkBuilder.toFile(outputFile);
    }

    /**
     * 根据字符串生成透明图片
     *
     * @param width
     * @param height
     * @param watermarkConfig
     * @return
     */
    BufferedImage drawTranslucentStringPic(int width, int height, WatermarkConfig watermarkConfig) {

        String content = watermarkConfig.getContent();

        //准备字体,并计算水印宽高
        //每个字符占用的平均宽作为字体的高
        int fontHeight = width / content.length();
        Font font = new Font(watermarkConfig.getFontName(), watermarkConfig.getFontStyle(), fontHeight);
        FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
        int extraWidth = fontHeight;
        int extraHeight = fontHeight / 2;
        int waterWidth = fm.stringWidth(content) + extraWidth;
        int waterHeight = fontHeight + extraHeight;

        BufferedImage buffImg = new BufferedImage(waterWidth, waterHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D gd = buffImg.createGraphics();
        //设置透明
        buffImg = gd.getDeviceConfiguration().createCompatibleImage(waterWidth, waterHeight, Transparency.TRANSLUCENT);
        gd = buffImg.createGraphics();
        gd.setFont(font);
        gd.setColor(watermarkConfig.getFontColor());
        int heightOffset = waterHeight - extraHeight / 2;
        int widthOffset = extraWidth / 2;
        gd.drawString(content, widthOffset, heightOffset);
        return buffImg;
    }

//    public static void main(String[] args) throws IOException {
//
//        String dir = "C:\\Users\\gelic\\Pictures\\test\\";
//        File file = new File(dir);
//        for(String fileName : file.list()) {
//            File f = tryGetFile(file, fileName);
//            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
//            String pureFilename = fileName.substring(0, fileName.lastIndexOf("."));
//            File outputFile = new File(dir + pureFilename + "_p." + fileExt);
////            WatermarkConfig watermarkConfig = new WatermarkConfig("FileInputStream 2018-09-12").setPositions(Positions.TOP_LEFT);
////            new ThumbnailsPicServiceImpl().watermark(new FileInputStream(f), "jpg", watermarkConfig, new FileOutputStream(outputFile));
//            new ThumbnailsPicServiceImpl().Thum(new FileInputStream(f), 1.0, 0.01f, new FileOutputStream(outputFile));
//        }
////            ImageInputStream imageInputStream = ImageIO.createImageInputStream(new FileInputStream(f));
////            Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(imageInputStream);
////            ImageReader imageReader = imageReaders.next();
////            String ext = f.getName().split("\\.")[1];
////            ImageIO.write(ImageIO.read(f), ext, new File(dir + "p_" + fileName));
//    }
}
